package jmu.edu.cn.action;

import java.util.Map;

import org.apache.struts2.interceptor.SessionAware;

import jmu.edu.cn.domain.Admin;
import jmu.edu.cn.domain.User;
import jmu.edu.cn.exception.LRSException;
import jmu.edu.cn.service.AdminService;
import jmu.edu.cn.service.AdminServiceImpl;
import jmu.edu.cn.service.UserService;
import jmu.edu.cn.service.UserServiceImpl;

public class SecurityAction extends BaseAction implements SessionAware {
	private User user;
	private Map<String, Object> session;

	private boolean who;

	public User getUser() {
		return user;
	}

	public void setUser(User user) {
		this.user = user;
	}

	public boolean isWho() {
		return who;
	}

	public void setWho(boolean who) {
		this.who = who;
	}

	public Map<String, Object> getSession() {
		return session;
	}

	public String toLogin() throws Exception {
		return "login_page";
	}

	public String login() throws Exception {
		UserService uService = new UserServiceImpl();
		AdminService aService = new AdminServiceImpl();
		try {
			if (who) {
				Admin admin = (Admin) user;
				if (admin == null)
					admin = new Admin();
				admin = aService.checkAdmin(admin.getUserNo(), admin.getUserPasswd());
				session.put("loginedUser", admin);
				return "admin_main";
			} else {
				if (user == null)
					user = new User();
				user = uService.checkUser(user.getUserNo(), user.getUserPasswd());
				session.put("loginedUser", user);
				return "user_main";
			}
		} catch (LRSException e) {
			this.addActionError(e.getMessage());
			return "login_page";
		}
	}

	@Override
	public void setSession(Map<String, Object> session) {
		this.session = session;
	}
}
